<?php
namespace app\zhongcan\controller;
use app\zhongcan\model\BannerModel;
use app\zhongcan\validate\BannerValidate;
use cmf\controller\AdminBaseController;

class BannerController extends AdminBaseController{
    //列表
    public function index()
    {
        $keyword=input('keyword','');
        // echo  $keyword;
        //存放条件
        $where=[];
        if($keyword){
            $where[]=['id','like','%'.$keyword.'%'];
        }
        $list= BannerModel::where($where)
            ->order('list_order','desc')
            ->paginate(3);
        $this->assign('banner',$list);
        return $this->fetch('index',[
            'banner'=>$list
        ]);
    }
    //显示添加页面
    public function add(){
        return $this->fetch('add');
    }
    public function addPost(){
        //接收
        $data=input('post.');
        $v=new BannerValidate();
        $r=$v->scene('add')->check($data);
        if(!$r){
            $this->error($v->getError());
        }
        $res=BannerModel::create($data);
        if($res){
            return json(['code' => 1,'msg' => '保存成功','data' => null]);
        }else{
            return json(['code' => 0,'msg' => '保存失败','data' => null]);
        }
    }
    //显示编辑页面
    public function edit(){
        $id=input('id/d');
        $banner = BannerModel::find($id);
        return $this->fetch('edit',[
            'banner'=>$banner
        ]);

    }
    public function editPost(){
        //接收
        $data=input('post.');
        $v=new BannerValidate();
        $r=$v->scene('edit')->check($data);
        if(!$r){
            $this->error($v->getError());
        }
        //接受数据
        $banner = BannerModel::find($data['id']);
        if(!$banner){
            $this->error('未查询到数据');
        }
        $banner->image=$data['image'];
        $banner->url=$data['url'];

        //入库
        if($banner->save()){
            $this->success('保存成功','Banner/index');
        }else{
            $this->error('保存失败','Banner/index');
        }
    }
    //删除
    public function del(){
        $id=input('id/d');
        $del=BannerModel::destroy( $id);
        if($del){
            $this->success('保存成功','banner/index');
        }else{
            $this->error('保存失败','banner/index');
        }
    }
    //排序
    public function order(){
        $order=parent::listOrders(new BannerModel());
        if($order){
            $this->success('排序成功','Banner/index');
        }else{
            $this->error('排序失败','Banner/index');
        }
    }
}